package com.lovely602.ai.alibaba.config;


import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeCloudStore;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeStoreOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 *
 * LLM配置
 *
 * @author lizhixing
 */
@Configuration
public class AiConfig {

    @Bean
    public ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你将作为一名Java开发语言的专家，对于用户的使用需求作出解答")
                .build();
    }

    /**
     * 简单的向量存储
     *
     * @param embeddingModel 嵌入模型
     * @return 向量存储
     */
    @Bean("simpleVectorStore")
    public SimpleVectorStore simpleVectorStore(EmbeddingModel embeddingModel) {

        SimpleVectorStore simpleVectorStore = SimpleVectorStore.builder(embeddingModel).build();
        //提取文本内容
        String filepath = "张三简历.txt";
        TextReader textReader = new TextReader(filepath);
        textReader.getCustomMetadata().put("filepath", filepath);
        List<Document> documents = textReader.get();

        //段落切分
        TokenTextSplitter splitter = new TokenTextSplitter(1200,
                350, 5,
                100, true);
        splitter.apply(documents);
        //向量化存储
        simpleVectorStore.add(documents);

        //生成说明文档
        List<Document> files = List.of(
                new Document("""
                        产品说明:名称：Java开发语言
                        产品描述：Java是一种面向对象开发语言。
                        特性：
                        1. 封装
                        2. 继承
                        3. 多态
                        """
                ));
        //向量化存储
        simpleVectorStore.add(files);

        return simpleVectorStore;
    }

    /**
     * dashscope云存储
     */
    @Bean("dashScopeCloudStore")
    public DashScopeCloudStore dashScopeCloudStore() {

        DashScopeApi dashScopeApi = DashScopeApi.builder().apiKey(System.getenv("AI_DASHSCOPE_API_KEY")).build();

        DashScopeStoreOptions options = new DashScopeStoreOptions("spring");

        return new DashScopeCloudStore(dashScopeApi, options);
    }

}
